package site.isscloud.project.mqtt;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import site.isscloud.framework.config.MqttConfig;
import site.isscloud.project.constants.BusinessConstants;

/**
 * 项目MQTT业务服务
 */
@Service
@ConditionalOnProperty(name = "mqtt.enabled", havingValue = "true")
public class ProjectMqttService {

    private static final Logger log = LoggerFactory.getLogger(ProjectMqttService.class);

    @Autowired
    private MqttConfig mqttConfig;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发布实时数据 (QoS 0)
     */
    public boolean publishRealtimeData(Object data) {
        String topic = BusinessConstants.MQTT_REALTIME_TOPIC;
        String message;

        try {
            message = objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            log.error("序列化实时数据失败", e);
            return false;
        }

        boolean success = mqttConfig.publish(topic, message, mqttConfig.getQos().get("realtime")); // QoS 0
        if (success) {
            log.debug("实时数据发布成功");
        } else {
            log.error("实时数据发布失败");
        }
        return success;
    }

    /**
     * 发布告警数据 (QoS 1)
     */
    public boolean publishAlarmData(Object alarmData) {
        String topic = BusinessConstants.MQTT_ALARM_TOPIC;
        String message;

        try {
            message = objectMapper.writeValueAsString(alarmData);
        } catch (Exception e) {
            log.error("序列化告警数据失败", e);
            return false;
        }

        boolean success = mqttConfig.publish(topic, message, mqttConfig.getQos().get("alarm")); // QoS 1
        if (success) {
            log.info("告警数据发布成功 - 主题: {}", topic);
        } else {
            log.error("告警数据发布失败 - 主题: {}", topic);
        }
        return success;
    }
}